import { NOVEL_DATA, NOVEL_LOCAL_DATA, LOCAL_KEY, state, stateoperation } from './index.js'
import { codeData, message, http } from './utlis.js'
export default {
	name: 'delItem',
	template: `#delItem`,
	setup() {
		// 更新页面
		const recoveryc = data => {
			stateoperation.delItem('dellist', data)
			stateoperation.addItem(data)
			// 更新本地数据
			localStorage.setItem(LOCAL_KEY.NOVEL_LOCAL_DATA, JSON.stringify(NOVEL_LOCAL_DATA))
			// 更新数据库缓存数据
			localStorage.setItem(LOCAL_KEY.NOVEL_DATA, JSON.stringify(NOVEL_DATA))
		}

		async function recoveryclk(item) {
			debugger
			try {
				const request = await http(
					'/novel/update',
					{
						isdel: 1,
						id: item.id,
					},
					'POST'
				)
				// 删除本地数据
				const localIndex = NOVEL_LOCAL_DATA.findIndex(lv => lv.title === item.title)
				NOVEL_LOCAL_DATA.splice(localIndex, 1)
				item.isdel = 1
				item.islocal = false
				if (request.length > 0) {
					item.id = request[0].id
				}
				// 加入到数据库缓存
				NOVEL_DATA.push(codeData(item))
				recoveryc(item)
				message('恢复成功')
			} catch (error) {
				console.log(error)
				// 请求失败
				// 既然请求失败，那就还是本地保存修改记录
				const localIndex = NOVEL_LOCAL_DATA.findIndex(lv => lv.title === item.title)
				item.isdel = 1
				NOVEL_LOCAL_DATA.splice(localIndex, 1, codeData(item))
				recoveryc(item)
				message('删除失败，本地保存')
			}
		}
		return { list: state.dellist, recoveryclk }
	},
}
